import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  InfoCircleOutlined,
  PlusOutlined,
  QuestionCircleOutlined,
  SaveOutlined,
} from "@ant-design/icons";
import {
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
} from "@ant-design/pro-components";
import {
  Alert,
  Button,
  Card,
  Col,
  Divider,
  Form,
  Input,
  Modal,
  Progress,
  Result,
  Row,
  Steps,
  Tooltip,
  Typography,
  message,
} from "antd";

import React, { useState } from "react";

import "./index.less";

const { Title, Paragraph } = Typography;

interface FormValues {
  basicInfo: {
    name: string;
    email: string;
    phone: string;
    website: string;
  };
  companyInfo: {
    companyName: string;
    industry: string;
    size: string;
    founded: string;
  };
  addressInfo: {
    country: string;
    province: string;
    city: string;
    address: string;
    postalCode: string;
  };
  contactPersons: {
    name: string;
    position: string;
    phone: string;
    email: string;
  }[];
  preferences: {
    notifications: string[];
    theme: string;
    language: string;
  };
  agreement: boolean;
}

const Page41: React.FC = () => {
  const [form] = Form.useForm();
  const [formValues, setFormValues] = useState<Partial<FormValues>>({});
  const [validationStatus, setValidationStatus] = useState<
    "none" | "error" | "warning" | "success"
  >("none");
  const [validationMessage, setValidationMessage] = useState<string>("");
  const [passwordStrength, setPasswordStrength] = useState<number>(0);
  const [passwordValidation, setPasswordValidation] = useState({
    length: false,
    uppercase: false,
    lowercase: false,
    number: false,
    special: false,
  });
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [formCompleted, setFormCompleted] = useState<boolean>(false);

  // 密码强度检查
  const checkPasswordStrength = (password: string) => {
    const validations = {
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
    };

    setPasswordValidation(validations);

    // 计算密码强度
    const strength = Object.values(validations).filter(Boolean).length * 20;
    setPasswordStrength(strength);

    return validations;
  };

  // 表单验证
  const validateForm = (values: any) => {
    // 模拟表单验证逻辑
    const errors = [];

    if (!values.basicInfo?.name) {
      errors.push("姓名不能为空");
    }

    if (!values.basicInfo?.email) {
      errors.push("邮箱不能为空");
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.basicInfo.email)) {
      errors.push("邮箱格式不正确");
    }

    if (!values.basicInfo?.phone) {
      errors.push("电话不能为空");
    } else if (!/^\d{11}$/.test(values.basicInfo.phone)) {
      errors.push("电话格式不正确（需要11位数字）");
    }

    if (
      values.basicInfo?.website &&
      !/^https?:\/\//.test(values.basicInfo.website)
    ) {
      errors.push("网站地址必须以http://或https://开头");
    }

    if (values.contactPersons && values.contactPersons.length > 0) {
      values.contactPersons.forEach((person: any, index: number) => {
        if (!person.name) {
          errors.push(`联系人${index + 1}的姓名不能为空`);
        }
        if (person.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(person.email)) {
          errors.push(`联系人${index + 1}的邮箱格式不正确`);
        }
      });
    }

    if (!values.agreement) {
      errors.push("您必须同意服务条款");
    }

    if (errors.length > 0) {
      setValidationStatus("error");
      setValidationMessage(`表单验证失败：${errors.join("；")}`);
      return false;
    } else if (passwordStrength < 60) {
      setValidationStatus("warning");
      setValidationMessage("警告：密码强度较弱，建议增强密码安全性");
      return true;
    } else {
      setValidationStatus("success");
      setValidationMessage("表单验证通过！");
      return true;
    }
  };

  // 提交表单
  const handleSubmit = (values: any) => {
    setFormValues(values);
    const isValid = validateForm(values);

    if (isValid) {
      message.success("表单提交成功！");
      setFormCompleted(true);
    } else {
      message.error("表单验证失败，请检查错误并重新提交");
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setValidationStatus("none");
    setValidationMessage("");
    setPasswordStrength(0);
    setPasswordValidation({
      length: false,
      uppercase: false,
      lowercase: false,
      number: false,
      special: false,
    });
    setFormValues({});
    setCurrentStep(0);
    setFormCompleted(false);
  };

  // 预览表单数据
  const handlePreview = () => {
    form
      .validateFields()
      .then((values) => {
        setFormValues(values);
        setPreviewVisible(true);
      })
      .catch((error) => {
        console.log("表单验证失败:", error);
      });
  };

  // 渲染密码强度指示器
  const renderPasswordStrengthIndicator = () => {
    let status = "exception";
    if (passwordStrength >= 60 && passwordStrength < 80) {
      status = "normal";
    } else if (passwordStrength >= 80) {
      status = "success";
    }

    return (
      <div style={{ marginBottom: 24 }}>
        <div style={{ marginBottom: 8 }}>密码强度：</div>
        <Progress
          percent={passwordStrength}
          status={status as "exception" | "normal" | "success" | undefined}
          showInfo={false}
          strokeWidth={8}
        />
        <div className="validation-rules">
          {Object.entries(passwordValidation).map(([key, value]) => {
            const labelMap: Record<string, string> = {
              length: "至少8个字符",
              uppercase: "至少包含1个大写字母",
              lowercase: "至少包含1个小写字母",
              number: "至少包含1个数字",
              special: "至少包含1个特殊字符",
            };

            return (
              <div className="rule-item" key={key}>
                {value ? (
                  <CheckCircleOutlined className="rule-icon success" />
                ) : (
                  <CloseCircleOutlined className="rule-icon error" />
                )}
                <span className="rule-text">{labelMap[key]}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  // 渲染验证状态
  const renderValidationStatus = () => {
    if (validationStatus === "none") return null;

    const statusConfig = {
      error: {
        icon: (
          <CloseCircleOutlined
            className="status-icon"
            style={{ color: "#f5222d" }}
          />
        ),
        text: validationMessage,
      },
      warning: {
        icon: (
          <ExclamationCircleOutlined
            className="status-icon"
            style={{ color: "#faad14" }}
          />
        ),
        text: validationMessage,
      },
      success: {
        icon: (
          <CheckCircleOutlined
            className="status-icon"
            style={{ color: "#52c41a" }}
          />
        ),
        text: validationMessage,
      },
    };

    const config = statusConfig[validationStatus];

    return (
      <div className={`validation-status ${validationStatus}`}>
        {config.icon}
        <div className="status-text">{config.text}</div>
      </div>
    );
  };

  // 如果表单已完成，显示成功结果
  if (formCompleted) {
    return (
      <div className="form-validation-page">
        <Result
          status="success"
          title="表单提交成功！"
          subTitle="您的信息已成功提交，我们将尽快处理您的申请。"
          extra={[
            <Button type="primary" key="console" onClick={handleReset}>
              创建新表单
            </Button>,
            <Button key="preview" onClick={() => setPreviewVisible(true)}>
              查看提交内容
            </Button>,
          ]}
        />
      </div>
    );
  }

  return (
    <div className="form-validation-page">
      <div className="page-header">
        <Title level={2} className="page-title">
          复杂表单验证系统
        </Title>
        <Paragraph className="page-description">
          演示高级表单验证功能，包括实时验证、密码强度检测、多步骤表单和动态表单项
        </Paragraph>
      </div>

      <Card className="form-container">
        <Steps
          current={currentStep}
          items={[
            {
              title: "基本信息",
              description: "个人基本信息",
            },
            {
              title: "公司信息",
              description: "公司相关信息",
            },
            {
              title: "联系人信息",
              description: "添加联系人",
            },
            {
              title: "确认信息",
              description: "确认并提交",
            },
          ]}
          style={{ marginBottom: 40 }}
        />

        <StepsForm
          form={form}
          current={currentStep}
          onCurrentChange={setCurrentStep}
          onFinish={handleSubmit}
          submitter={{
            render: (props) => {
              if (props.step === 3) {
                return [
                  <Button key="reset" onClick={handleReset}>
                    重置
                  </Button>,
                  <Button
                    key="preview"
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                  >
                    预览
                  </Button>,
                  <Button
                    type="primary"
                    key="submit"
                    onClick={() => props.onSubmit?.()}
                    icon={<SaveOutlined />}
                  >
                    提交
                  </Button>,
                ];
              }

              return [
                props.step > 0 && (
                  <Button key="pre" onClick={() => props.onPre?.()}>
                    上一步
                  </Button>
                ),
                <Button
                  type="primary"
                  key="next"
                  onClick={() => props.onSubmit?.()}
                >
                  {props.step === 3 ? "提交" : "下一步"}
                </Button>,
              ];
            },
          }}
        >
          <StepsForm.StepForm
            name="basicInfo"
            title="基本信息"
            onFinish={async () => {
              return true;
            }}
          >
            <ProFormText
              name={["basicInfo", "name"]}
              label="姓名"
              placeholder="请输入姓名"
              rules={[{ required: true, message: "请输入姓名" }]}
              fieldProps={{
                prefix: <InfoCircleOutlined />,
              }}
            />

            <ProFormText
              name={["basicInfo", "email"]}
              label="邮箱"
              placeholder="请输入邮箱"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "邮箱格式不正确" },
              ]}
              fieldProps={{
                prefix: <InfoCircleOutlined />,
              }}
            />

            <ProFormText
              name={["basicInfo", "phone"]}
              label="电话"
              placeholder="请输入电话"
              rules={[
                { required: true, message: "请输入电话" },
                {
                  pattern: /^\d{11}$/,
                  message: "电话格式不正确（需要11位数字）",
                },
              ]}
              fieldProps={{
                prefix: <InfoCircleOutlined />,
              }}
            />

            <ProFormText
              name={["basicInfo", "website"]}
              label="网站"
              placeholder="请输入网站地址"
              rules={[
                {
                  pattern: /^https?:\/\//,
                  message: "网站地址必须以http://或https://开头",
                },
              ]}
              fieldProps={{
                prefix: <InfoCircleOutlined />,
              }}
            />

            <ProForm.Item
              name={["basicInfo", "password"]}
              label={
                <span>
                  密码
                  <Tooltip title="密码必须包含大小写字母、数字和特殊字符">
                    <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                  </Tooltip>
                </span>
              }
              rules={[
                { required: true, message: "请输入密码" },
                {
                  validator: (_, value) => {
                    const validations = checkPasswordStrength(value || "");
                    const allValid = Object.values(validations).every(Boolean);
                    return allValid
                      ? Promise.resolve()
                      : Promise.reject(new Error("密码不符合安全要求"));
                  },
                },
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </ProForm.Item>

            {renderPasswordStrengthIndicator()}

            <ProForm.Item
              name={["basicInfo", "confirmPassword"]}
              label="确认密码"
              rules={[
                { required: true, message: "请确认密码" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (
                      !value ||
                      getFieldValue(["basicInfo", "password"]) === value
                    ) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次输入的密码不一致"));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </ProForm.Item>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="companyInfo"
            title="公司信息"
            onFinish={async () => {
              return true;
            }}
          >
            <ProFormText
              name={["companyInfo", "companyName"]}
              label="公司名称"
              placeholder="请输入公司名称"
              rules={[{ required: true, message: "请输入公司名称" }]}
            />

            <ProFormSelect
              name={["companyInfo", "industry"]}
              label="所属行业"
              placeholder="请选择所属行业"
              options={[
                { label: "互联网/IT", value: "it" },
                { label: "金融/银行", value: "finance" },
                { label: "教育/培训", value: "education" },
                { label: "医疗/健康", value: "health" },
                { label: "制造业", value: "manufacturing" },
                { label: "其他", value: "other" },
              ]}
              rules={[{ required: true, message: "请选择所属行业" }]}
            />

            <ProFormSelect
              name={["companyInfo", "size"]}
              label="公司规模"
              placeholder="请选择公司规模"
              options={[
                { label: "1-10人", value: "xs" },
                { label: "11-50人", value: "sm" },
                { label: "51-200人", value: "md" },
                { label: "201-500人", value: "lg" },
                { label: "501-1000人", value: "xl" },
                { label: "1000人以上", value: "xxl" },
              ]}
              rules={[{ required: true, message: "请选择公司规模" }]}
            />

            <ProFormDatePicker
              name={["companyInfo", "founded"]}
              label="成立日期"
              placeholder="请选择成立日期"
              rules={[{ required: true, message: "请选择成立日期" }]}
            />

            <Divider dashed />

            <ProFormText
              name={["addressInfo", "country"]}
              label="国家/地区"
              placeholder="请输入国家/地区"
              rules={[{ required: true, message: "请输入国家/地区" }]}
            />

            <Row gutter={16}>
              <Col span={12}>
                <ProFormText
                  name={["addressInfo", "province"]}
                  label="省份"
                  placeholder="请输入省份"
                  rules={[{ required: true, message: "请输入省份" }]}
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  name={["addressInfo", "city"]}
                  label="城市"
                  placeholder="请输入城市"
                  rules={[{ required: true, message: "请输入城市" }]}
                />
              </Col>
            </Row>

            <ProFormTextArea
              name={["addressInfo", "address"]}
              label="详细地址"
              placeholder="请输入详细地址"
              rules={[{ required: true, message: "请输入详细地址" }]}
            />

            <ProFormText
              name={["addressInfo", "postalCode"]}
              label="邮政编码"
              placeholder="请输入邮政编码"
              rules={[
                { required: true, message: "请输入邮政编码" },
                {
                  pattern: /^\d{6}$/,
                  message: "邮政编码格式不正确（需要6位数字）",
                },
              ]}
            />
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="contactPersons"
            title="联系人信息"
            onFinish={async () => {
              return true;
            }}
          >
            <Alert
              message="请添加至少一位联系人"
              description="联系人信息将用于我们与贵公司的沟通和联系。"
              type="info"
              showIcon
              style={{ marginBottom: 24 }}
            />

            <ProFormList
              name="contactPersons"
              label="联系人列表"
              creatorButtonProps={{
                creatorButtonText: "添加联系人",
                icon: <PlusOutlined />,
              }}
              min={1}
              copyIconProps={false}
              itemRender={({ listDom, action }, { index }) => (
                <Card
                  title={`联系人 ${index + 1}`}
                  className="dynamic-form-item"
                  key={index}
                  extra={action}
                  bordered={false}
                >
                  {listDom}
                </Card>
              )}
              creatorRecord={{ name: "", position: "", phone: "", email: "" }}
            >
              <ProFormText
                name="name"
                label="姓名"
                placeholder="请输入联系人姓名"
                rules={[{ required: true, message: "请输入联系人姓名" }]}
              />
              <ProFormText
                name="position"
                label="职位"
                placeholder="请输入联系人职位"
              />
              <ProFormText
                name="phone"
                label="电话"
                placeholder="请输入联系人电话"
                rules={[
                  {
                    pattern: /^\d{11}$/,
                    message: "电话格式不正确（需要11位数字）",
                  },
                ]}
              />
              <ProFormText
                name="email"
                label="邮箱"
                placeholder="请输入联系人邮箱"
                rules={[{ type: "email", message: "邮箱格式不正确" }]}
              />
            </ProFormList>
          </StepsForm.StepForm>

          <StepsForm.StepForm
            name="confirm"
            title="确认信息"
            onFinish={async (values) => {
              console.log("表单提交的值:", values);
              return true;
            }}
          >
            <div className="form-section">
              <h3 className="section-title">偏好设置</h3>

              <ProFormCheckbox.Group
                name={["preferences", "notifications"]}
                label="通知方式"
                options={[
                  { label: "邮件通知", value: "email" },
                  { label: "短信通知", value: "sms" },
                  { label: "应用内通知", value: "app" },
                ]}
              />

              <ProFormRadio.Group
                name={["preferences", "theme"]}
                label="界面主题"
                options={[
                  { label: "浅色模式", value: "light" },
                  { label: "深色模式", value: "dark" },
                  { label: "跟随系统", value: "system" },
                ]}
                initialValue="light"
              />

              <ProFormSelect
                name={["preferences", "language"]}
                label="语言偏好"
                options={[
                  { label: "简体中文", value: "zh-CN" },
                  { label: "繁体中文", value: "zh-TW" },
                  { label: "英语", value: "en-US" },
                  { label: "日语", value: "ja-JP" },
                ]}
                initialValue="zh-CN"
              />
            </div>

            <Divider />

            <ProFormCheckbox
              name="agreement"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error("您必须同意服务条款")),
                },
              ]}
            >
              我已阅读并同意 <a href="#terms">服务条款</a> 和{" "}
              <a href="#privacy">隐私政策</a>
            </ProFormCheckbox>

            {renderValidationStatus()}
          </StepsForm.StepForm>
        </StepsForm>
      </Card>

      <Modal
        title="表单数据预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="back" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={() => {
              setPreviewVisible(false);
              form.submit();
            }}
          >
            确认提交
          </Button>,
        ]}
        width={700}
      >
        <div className="form-preview">
          <div className="preview-title">基本信息</div>
          <div className="preview-item">
            <div className="preview-label">姓名：</div>
            <div className="preview-value">{formValues.basicInfo?.name}</div>
          </div>
          <div className="preview-item">
            <div className="preview-label">邮箱：</div>
            <div className="preview-value">{formValues.basicInfo?.email}</div>
          </div>
          <div className="preview-item">
            <div className="preview-label">电话：</div>
            <div className="preview-value">{formValues.basicInfo?.phone}</div>
          </div>
          <div className="preview-item">
            <div className="preview-label">网站：</div>
            <div className="preview-value">
              {formValues.basicInfo?.website || "无"}
            </div>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default Page41;
